package interactive

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

// Receive 接收输入
func Receive(message string, empty bool) (string, error) {
	var scanner = bufio.NewScanner(os.Stdin)

	for {
		fmt.Printf("%s。输入完成后请按回车键: ", message)
		if scanner.Scan() {
			if nil != scanner.Err() {
				return "", scanner.Err()
			}

			var value = strings.TrimSpace(scanner.Text())
			if !empty && "" == value {
				continue
			}

			return value, nil
		}
	}
}

// ReceiveWithLength 接收指定长度范围的输入内容
func ReceiveWithLength(message string, min int, max int, empty bool) (string, error) {
	var scanner = bufio.NewScanner(os.Stdin)

	for {
		fmt.Printf("%s。输入完成后请按回车键: ", message)
		if scanner.Scan() {
			if nil != scanner.Err() {
				return "", scanner.Err()
			}

			var value = strings.TrimSpace(scanner.Text())
			if !empty && "" == value {
				continue
			}

			if min > len(value) || len(value) > max {
				continue
			}

			return value, nil
		}
	}
}

// ReceiveInteger 接收数字类型输入
func ReceiveInteger(message string, min int, max int, empty bool) (int, error) {
	var scanner = bufio.NewScanner(os.Stdin)

	for {
		fmt.Printf("%s。输入完成后请按回车键: ", message)
		if scanner.Scan() {
			if nil != scanner.Err() {
				return 0, scanner.Err()
			}

			var value = strings.TrimSpace(scanner.Text())
			if !empty && "" == value {
				continue
			}

			v, err := strconv.Atoi(value)
			if nil != err {
				fmt.Println("请输入有效数字")

				continue
			}

			if v < min {
				fmt.Printf("数字范围不能小于: %d\n", min)

				continue
			}

			if v > max {
				fmt.Printf("数字范围不能大于: %d\n", min)

				continue
			}

			return v, nil
		}
	}
}

// ReceiveIntegerWithDefault 接收数字输入，允许设置默认值
func ReceiveIntegerWithDefault(message string, min int, max int, d int) (int, error) {
	var scanner = bufio.NewScanner(os.Stdin)

	for {
		fmt.Printf("%s，输入完成后请按回车键。此选项拥有默认值，默认值为[%d]，若使用默认值请直接输入回车键: ", message, d)
		if scanner.Scan() {
			if nil != scanner.Err() {
				return 0, scanner.Err()
			}

			var value = strings.TrimSpace(scanner.Text())
			if "" == value {
				return d, nil
			}

			v, err := strconv.Atoi(value)
			if nil != err {
				fmt.Println("请输入有效数字")

				continue
			}

			if v < min {
				fmt.Printf("数字范围不能小于: %d\n", min)

				continue
			}

			if v > max {
				fmt.Printf("数字范围不能大于: %d\n", min)

				continue
			}

			return v, nil
		}
	}
}
